package com.tdam2014.grupo3.tasks;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.widget.Toast;

import com.tdam2014.grupo3.PeopleFragment;
import com.tdam2014.grupo3.R;
import com.tdam2014.grupo3.db.PeopleDatabaseHelper;
import com.tdam2014.grupo3.entities.People;
import com.tdam2014.grupo3.flickr.Flickr;
import com.tdam2014.grupo3.flickr.FlickrException;
import com.tdam2014.grupo3.flickr.interfaces.PeopleInterface;
import com.tdam2014.grupo3.flickrviewer.FlickrViewer;

public class FindPeopleTask extends AsyncTask<String, Object, Boolean> {
	
	private PeopleFragment peopleFragment;
	private People people;
	private ProgressDialog progressDialog;
	
	public FindPeopleTask(PeopleFragment personFragment) {
		super();
		this.peopleFragment = personFragment;
	}
	
	@Override
	protected void onPreExecute() {
		progressDialog = new ProgressDialog(peopleFragment.getActivity());
		progressDialog.setCancelable(false);
		progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		        cancel(true);
		    }
		});
		progressDialog.show();
	}

	@Override
	protected Boolean doInBackground(String... params) {
		progressDialog.setMessage(peopleFragment.getResources().getString(R.string.finding_user) + " " + params[0]);
		
		Flickr flickr = new Flickr(FlickrViewer.API_KEY);
		PeopleInterface pi = flickr.getPeopleInterface();
		
		try {
			people = pi.findByUsername(params[0]);
		} catch (FlickrException flickrException) {
			return Boolean.TRUE;
		} catch (Exception e) {
			return Boolean.FALSE;
		}
		
		return Boolean.TRUE;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		progressDialog.dismiss();
		
		if(result) {
			if(people != null) {
				PeopleDatabaseHelper personDatabaseHelper = new PeopleDatabaseHelper(peopleFragment.getActivity());
				personDatabaseHelper.addPeople(people);
				
				peopleFragment.endSearchUser(people);
			} else {
				Toast error = Toast.makeText(peopleFragment.getActivity(), peopleFragment.getResources().getString(R.string.error_finding_user), Toast.LENGTH_SHORT);
				error.show();
			}
		} else {
			Toast error = Toast.makeText(peopleFragment.getActivity(), peopleFragment.getResources().getString(R.string.user_not_exists), Toast.LENGTH_SHORT);
			error.show();
		}
	}
	
	@Override
	protected void onCancelled() {
		super.onCancelled();
		progressDialog.dismiss();
	}
}